import { useParams, useNavigate } from 'react-router-dom';
import { Button, Form, Input, DatePicker, Select, message } from 'antd';
import { useEffect, useState } from 'react';
import { updateOrder, getOrderById } from '../../services/order';

import dayjs from 'dayjs';
const { Option } = Select;

export default function OrderEdit() {
  const { id } = useParams();
  const navigate = useNavigate();
  const [form] = Form.useForm();
  const [order, setOrder] = useState({});
  const layout = {
    labelCol: {
      span: 8,
    },
    wrapperCol: {
      span: 16,
    },
  };

  const validateMessages = {
    required: '请输入${label}',
  };

  useEffect(() => {
    if (id) {
      getOrderById(id).then((response) => {
        const { code, result } = response.data;
        if (code === 1 && result) {
          const data = { ...result, createTime: dayjs(result.createTime) };
          setOrder(data);
          form.setFieldsValue(data);
        }
      });
    }
  }, []);

  const onFinish = (values) => {
    const data = {
      ...order,
      ...values,
      createTime: values.createTime.format('YYYY-MM-DD HH:mm:ss'),
    };

    updateOrder(id, data).then((response) => {
      console.log(response.data);
      const { code, msg } = response.data;
      if (code === 1) {
        message.success(msg);
        navigate('/order');
      }
    });
  };

  return (
    <Form
      {...layout}
      name="nest-messages"
      form={form}
      onFinish={onFinish}
      style={{
        maxWidth: 600,
      }}
      validateMessages={validateMessages}
    >
      <Form.Item name="orderId" label="订单ID" rules={[{ required: true }]}>
        <Input />
      </Form.Item>
      <Form.Item name="createTime" label="创建时间" rules={[{ required: true }]}>
        <DatePicker showTime format="YYYY-MM-DD HH:mm:ss" placeholder="请选择时间" />
      </Form.Item>
      <Form.Item name="status" label="订单状态" rules={[{ required: true }]}>
        <Select placeholder="请选择订单状态">
          <Option value="已完成">已完成</Option>
          <Option value="待发货">待发货</Option>
          <Option value="已发货">已发货</Option>
          <Option value="取消">取消</Option>
        </Select>
      </Form.Item>
      <Form.Item
        wrapperCol={{
          ...layout.wrapperCol,
          offset: 8,
        }}
      >
        <Button type="primary" htmlType="submit">
          确认
        </Button>
      </Form.Item>
    </Form>
  );
}
